/*
 * Created on 07.01.2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package org.jchains.receiver;


import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.logging.Level;

import org.jchains.CORBA.PermissionTransferPOA;
import org.jchains.CORBA.PermissionTransferPackage.CPermission;
import org.jchains.CORBA.PermissionTransferPackage.EnvironmentEntry;
import org.jchains.internal.Util;
import org.jchains.receiver.gui.GUIManagement;
import org.jchains.receiver.gui.ReceiverForm;
import org.omg.CORBA.ORB;



public class PermissionTransferServant extends PermissionTransferPOA {

	static final String filesep = System.getProperty("file.separator");
	static String javatmpdirprefix = System.getProperty("java.io.tmpdir");

	static final java.util.logging.Logger log = java.util.logging.Logger
			.getLogger("JChains");

	public final static int RECORDING_MODE_INTERACTIVE = 2;
	public final static int RECORDING_MODE_SILENT = 1;

	static String savedirprefix = System.getProperty(
			"org.jchains.SaveDirPrefix", javatmpdirprefix);

	static {
		log.info("using savedir: " + savedirprefix);
	}

	int anzahl = 0;

	private EnvironmentEntry[] ee = new EnvironmentEntry[0];

	private Vector<Perm> perms = new Vector<Perm>();

	private ORB orb;

	PolicyFile pf = null;
	boolean pref_GUI = true;
	// private PrintWriter pw_env;
	private PrintWriter pw_log;
	int recordingmode = RECORDING_MODE_INTERACTIVE;

	public PermissionTransferServant(ORB orb) {
		this.orb = orb;
		this.recordingmode = RECORDING_MODE_INTERACTIVE;
		this.pref_GUI = !Boolean.getBoolean("org.jchains.noGUI");
		System.out.println(orb == null ? "" : orb.toString());
	}

	public PermissionTransferServant() {
		this.recordingmode = RECORDING_MODE_INTERACTIVE;
		this.pref_GUI = !Boolean.getBoolean("org.jchains.noGUI");
		System.out.println(orb == null ? "" : orb.toString());
	}

	public void close(int sid) {
		try {
			pf.save();
			if (this.pref_GUI) {
				ReceiverForm fr = gp.getReceiverForm();
				fr.getFieldTxtMode().setText("finished");
				fr.getFieldTxtPolicyFile().setText(pf.getContent(true));
			}
			// fos.close();
			pw_log.close();
		} catch (Exception e) {
			log.info(e.getMessage());
			log.log(Level.WARNING, "", e);
			;
		} finally {

		}
	}

	private PrintWriter getIncrementalFile(String filename, int incname) {
		FileOutputStream fosret = null;
		PrintWriter pw = null;
		File f = new File(filename);
		boolean end = false;
		for (int i = 0; end; i++) {
			if (!f.exists()) {
				end = true;
			} else {
				f = new File(filename + incname);
				incname++;
			}
		}

		try {
			fosret = new FileOutputStream(f);
			pw = new PrintWriter(fosret, true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return pw;
	}

	

	public int init(String filename, EnvironmentEntry[] pe) {
		anzahl = 0;
		try {

			// ee = pe;

			if (pref_GUI) {
				gp = new GUIManagement();
				gp.initGUI(pe);
				log.info("init gui!");

			} else {
				log.info("no gui!");
			}
			savefilename = savedirprefix + filesep
					+ Util.tidyFilename(filename);
			policyfilename = savefilename + ".policy";
			envfilename = savefilename + ".env";

			int incname = 1;
			pw_log = getIncrementalFile(savefilename, incname);
			// pw_env = getIncrementalFile(envfilename, incname);
			pf = new PolicyFile(policyfilename, pe);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	GUIManagement gp;
	private String savefilename;
	private String envfilename;
	private String policyfilename;

	boolean b_tofile = false;

	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.illegalaccess.jchains.CORBA.PermissionTransferOperations#send(int,
	 * org.illegalaccess.jchains.CORBA.PermissionTransferPackage.CPermission)
	 */
	public void send(int sid, CPermission p) {
		// TODO Auto-generated method stub
		// 

		if (p.cn.startsWith("sun."))
			return;

		if (p.cn.startsWith("java."))
			return;

		if (p.cn.startsWith("javax."))
			return;

		long theTime = System.currentTimeMillis();
		Perm pe = new Perm(theTime, p, ee);
		// log.info("perm built");
		boolean isnew = pf.add(pe);
		if (!isnew)
			return;
		perms.add(pe);

		try {

			anzahl++;
			if (recordingmode != RECORDING_MODE_SILENT) {
				// String theActions = concat(',', p.actions);

				if (b_tofile) {
					pw_log.print(p.pt);
					pw_log.print(' ');
					pw_log.print(p.cb);
					pw_log.print(' ');
					pw_log.print(p.target);
					pw_log.print(' ');
				}
				// pw_log.println(theActions);
				// System.out.println(p.cb);
				// System.err.println(p.cb);
				// Perm pe = new Perm(theTime, p.cb, p.pt, p.target,
				// theActions);
				// log.info("perm not built");
				if (anzahl % 50 == 0) {
					/*
					 * if (pref_GUI) { // log.info("File gui"); //
					 * stem.out.println("pref_gui:"+new Boolean(pref_GUI));
					 * frm_rf.tfTxtTime.setText(anzahl + ""); //
					 * frm_rf.tfTxtDate.setText(new Date()+"");
					 * frm_rf.tfPermActions.setText(pe.getFlatActions());
					 * frm_rf.tfPermType.setText(p.pt);
					 * frm_rf.tfPermTarget.setText(p.target); //
					 * frm_rf.tfPermTarget.setText(pe.getCurrent().methodname);
					 * frm_rf.tfPermCodebase.setText(p.cb);
					 * frm_rf.tfTxtLog.setText(savefilename);
					 * frm_rf.tfTxtPolicy.setText(policyfilename);
					 * frm_rf.tfPermTime
					 * .setText(PermTableModel.getShortTimeFromLong(pe.time));
					 * frm_rf.tfTxtMode.setText("running"); }
					 */
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Throwable t) {
			log.info(t.getClass().toString());
			log.log(Level.ALL, "unknown", t);
		}
	}

}
